﻿/*
Copyright (c) <2007> <Juan Pablo Califano (jpcalifano@gmail.com)>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

class ar.com.califa010.utils.ClassUtils {

	private function ClassUtils() {
	}

	
	public static function forName(className:String):Function {
		if(className == undefined || className == null) {
		//	throw new IllegalArgumentError("'" + className + "' is not allowed.");
		}		
		var c:Function = eval("_global." + className);
		if ( c == undefined ) {
		//	throw new ClassNotFoundError(className);
		}
		return c;
	}	
	/*
	basado en función publicada en:
	http://www.domestika.org/foros/viewtopic.php?t=50969
	
	public static function generateExcludeXML():Void {
	   trace("<excludeAssets>");
	   var showClasses:Function = function(nameSpace:Object, packageName:String):Void {
		  for (var i:String in nameSpace) {
			 if (typeof(nameSpace[i])=="function") {
				trace('\t<asset name="'+packageName+i+'" />');
			 } else {
				showClasses(nameSpace[i], packageName+i+".");
			 }
		  }
	   };
	   showClasses(_global, "");
	   trace("</excludeAssets>");
	}
	*/
	
	public static function generateExcludeXML(arrFilters:Array):String {
	//	trace("ClassUtils::generateExcludeXML()");
	
		var sExcludeXml:String = "<excludeAssets>\n";
		var arrClasses:Array = [];
		//	el scope es la clase porque el método addAssetItem es estático
		//	los parámetros que se pasan son una ref al array que va guardando todas las
		//	clases encontradas en _global, y un array de filtros, que se chequea 
		//	antes de agregar una clase a arrClasses
		mapClasses(_global, "",ClassUtils,addAssetItem,[arrClasses,arrFilters]);
		sExcludeXml += arrClasses.join("\n");
		sExcludeXml += "\n</excludeAssets>";
		return sExcludeXml;
	}
	/*
	Devuelve el nombre del xml de exclusión de clases para el swf que lo llame
	*/
	public static function getExcludeFileName():String {
				
		//	tomar la url, limpirla, hacer un split por "/", 
		//	tomar el último elemento, descartar la extensión y concatenar con "_exclude.xml"
		
		var swf:String = _root._url;
		var aux_lv:LoadVars = new LoadVars();
		aux_lv.decode("swf="+swf);
		swf = (aux_lv.swf).split("/").pop().split(".")[0];
		delete aux_lv;
	//	trace("swf="+swf);
		return swf + "_exclude.xml";	
	}
	
	private static function addAssetItem(path:String,arr:Array):Void {
		/*
		trace("ClassUtils::addAssetItem()");
		trace("path="+path);
		trace("arr="+arr);
		trace("arrClasses="+arr[0]);
		*/
		var arrClasses:Array = arr[0];
		var arrFilters:Array = arr[1].slice();

		if(!isInFilter(path,arrFilters)) {
			arrClasses.push(formatAssetItem(path));
		}
	}
	/*
	Esta función indica si el path pasado es igual a alguno de los filtros pasados
	Tiene en cuenta el "*" al buscar coincidencias
	*/
	private static function isInFilter(srcPath:String,arrFilters:Array):Boolean {
		var isFiltered:Boolean = false;
		
		var len:Number = arrFilters.length;
		var arrSrcPath:Array = srcPath.split(".");
		
		var filter:Array;
		var filterLen:Number;
		var leaf:String;
		var comparableLength:Number;
		
		for(var i:Number = 0;i<len;i++) {
		
			filter = arrFilters[i].split(".");
			filterLen = filter.length;
			leaf = String(filter[filterLen-1]);	
			
			if(leaf == "*") {
				filterLen--;
			} 
			
			if(ClassUtils.arrayEquals(arrSrcPath.slice(0,filterLen),filter.slice(0,filterLen))) {
				isFiltered = true;
				break;
			}
		
		}		
		
		return isFiltered;
	}
	
	private static function formatAssetItem(path:String):String {
		return '\t<asset name="'+path+'" />';
	}
	
	public static function getCompiledClassesString(arrFilter:Array):String {
	//	trace("ClassUtils::getCompiledClassesString()");
		return getCompiledClassesArray(arrFilter).join("\n");
	}
	
	public static function getCompiledClassesArray(arrFilter:Array):Array {
		var arrClasses:Array = [];
		
		mapClasses(_global, "",ClassUtils,applyFilter,[arrClasses,arrFilter]);
	//	trace("arrClasses="+arrClasses);	
		return arrClasses;
	}
	
	private static function applyFilter(path:String,arr:Array):Void {
		var arrClasses:Array = arr[0];
		var arrFilters:Array = arr[1].slice();

		if(!isInFilter(path,arrFilters)) {
			arrClasses.push(path);
		}
	}
	
	/*
	Función genérica interna que recorre todas las clases y llama a una función que se pasa 
	por parámetro, con el scope indicado, y dos argumentos: 
		1) el nombre calificado de la clase
		2) un array, opcional
	*/
	private static function mapClasses(nameSpace:Object,packageName:String,scope:Object,
									   fnc:Function,args:Array):Void {
		/*
		trace("ClassUtils::mapClasses()");
		trace("fnc="+fnc);
		trace("scope="+scope);
		*/
		
		for(var s:String in nameSpace) {
			if (typeof(nameSpace[s])=="function") {
				if(args) {
					fnc.call(scope,packageName+s,args);
				} else {
					fnc.call(scope,packageName+s);
				}	
			} else {
				mapClasses(nameSpace[s], packageName+s+".",scope,fnc,args);
			}
		}
	}
	
	private static function arrayEquals(a:Array,b:Array):Boolean {
		var len:Number = a.length;
		if(len != b.length) {
			return false;
		}
		var areEqual:Boolean = true;
		for(var i:Number = 0;i<len;i++) {
			if(a[i] != b[i]) {
				areEqual = false;
				break;
			}
		}
		return areEqual;
	}	
}
